package com.security.extractor;

import com.security.controller.OauthController;
import com.security.handler.Oauth2ParamsHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 陈圣融 on 2017-07-31.
 */
public class Oauth2BearerTokenExtractor extends BearerTokenExtractor {
    private final static Log logger = LogFactory.getLog(Oauth2BearerTokenExtractor.class);
    private Oauth2ParamsHandler oauth2ParamsHandler = new Oauth2ParamsHandler();

    protected String extractToken(HttpServletRequest request) {
        // first check the header...
        if (oauth2ParamsHandler.isNoCheckUrl(request)) {
            return null;
        }

        String token = extractHeaderToken(request);

        // bearer type allows a request parameter as well
        if (token == null) {
            logger.debug("Token not found in headers. Trying request parameters.");
            token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
            if (token == null) {
                logger.debug("Token not found in request parameters.  Not an OAuth2 request.");
            } else {
                request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE);
            }
        }

        return token;
    }

    public Oauth2ParamsHandler getOauth2ParamsHandler() {
        return oauth2ParamsHandler;
    }

    public void setOauth2ParamsHandler(Oauth2ParamsHandler oauth2ParamsHandler) {
        this.oauth2ParamsHandler = oauth2ParamsHandler;
    }
}
